package cn.libinal.scloud.winter.service.impl;

import cn.libinal.scloud.base.common.service.impl.AbstractJpaServiceImpl;
import cn.libinal.scloud.base.common.web.DataPageRequest;
import cn.libinal.scloud.base.common.web.ResultPage;
import cn.libinal.scloud.winter.domain.ProductVo;
import cn.libinal.scloud.winter.entity.Product;
import cn.libinal.scloud.winter.entity.QProduct;
import cn.libinal.scloud.winter.repository.ProductRepository;
import cn.libinal.scloud.winter.service.ProductService;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

/**
 * @author libinal
 */
@Service
public class ProductServiceImpl extends AbstractJpaServiceImpl<Product, ProductRepository> implements ProductService {

    private final QProduct qProduct = QProduct.product;
    private final DtoMapper dtoMapper;
    public ProductServiceImpl(ProductRepository repository, DtoMapper dtoMapper) {
        super(repository);
        this.dtoMapper = dtoMapper;
    }

    @Override
    public Predicate buildPagingPredicates(Product product) {
        BooleanBuilder builder = new BooleanBuilder();
        if (StringUtils.isNotBlank(product.getName())) {
            builder.and(qProduct.name.contains(product.getName()));
        }
        return builder;
    }

    @Override
    public ResultPage<ProductVo> queryByPaging(Predicate predicate, DataPageRequest pageRequest) {
        Page<Product> page = findByPaging(predicate, pageRequest);
        Page<ProductVo> pageVo = page.map(product -> dtoMapper.map(product, ProductVo.class));
        return ResultPage.buildPage(pageVo);
    }
}
